package com.chinamsp.baisc.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * 承载 application 上下文
 * @author shifenghu
 *
 */
@Service
public class ApplicationContextAccessor implements ApplicationContextAware{
	
	private static ApplicationContext applicationContext;
	
	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ApplicationContextAccessor.applicationContext = applicationContext;
	}
	
	/**
	 * 注意方法使用前提为当前类必须被Spring容器初始化
	 * @param beanName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName) {
		return (T) applicationContext.getBean(beanName);
	}
	/**
	 * 根据class类型从spring 容器初始化bean
	 * @param beanClass testbean class
	 * @return 实体
	 */
	public static <T> T getBean(Class<T> beanClass){
		return (T) applicationContext.getBean(beanClass);
	}
	
	/**
	 * 获取bean 列表
	 * @param <T>
	 * @param beanClass
	 * @return
	 */
	public static <T> List<T> getBeans(Class<T> beanClass){
		Map<String, T> beans = (Map<String, T>) applicationContext.getBeansOfType(beanClass);
		return new ArrayList<T>(beans.values());
	}
	
	/**
	 * 获取 testbean class 的子类列表
	 * @param <T>
	 * @param beanClass
	 * @return
	 */
	public static <T> Map<String, T> getBeansOfType(Class<T> beanClass){
		return applicationContext.getBeansOfType(beanClass);
	}
	
	/**
	 * 获取 app 上下文
	 * @return
	 */
	public static ApplicationContext getContext(){
		return applicationContext;
	}
	
	/**
	 * 获取bean 列表
	 * @param <T>
	 * @param beanClass
	 * @return
	 */
	public static <T> List<T> getBeans(Class<T> beanClass, ApplicationContext applicationContext){
		Map<String, T> beans = (Map<String, T>) applicationContext.getBeansOfType(beanClass);
		return new ArrayList<T>(beans.values());
	}
}
